package com.wis.bolt.common;

import com.alibaba.fastjson.JSONObject;
import com.wis.pool.redisCluster.MyJedisClusterPool;
import com.wis.tools.CommonUtiles;
import org.apache.commons.lang.StringUtils;
import org.apache.storm.task.OutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.topology.base.BaseRichBolt;
import org.apache.storm.tuple.Fields;
import org.apache.storm.tuple.Tuple;
import org.apache.storm.tuple.Values;
import redis.clients.jedis.JedisCluster;

import java.util.List;
import java.util.Map;

/**
 * @Description: traffic_wis    按照省份进行切割
 * @author: z1042
 * @Date: Created in 2018/12/13 20:01
 * @Modified By:
 */
public class PACSplitBolt extends BaseRichBolt {
    private OutputCollector collector;
    private static JSONObject jsonPAC = new JSONObject();
    private static List lrange;
    private static String pac = new String();

    @Override
    public void prepare(Map map, TopologyContext topologyContext, OutputCollector collector) {
        this.collector = collector;
        lrange = new CommonUtiles().getHttpList(map.get("queryFilter").toString());
        jsonPAC = new CommonUtiles().getHttpJsonObject(map.get("queryPac").toString());
    }

    // 接收：过来的是key，redis的key值，桩点id
    // 发送：发送的是key，redis的key值，桩点id
    @Override
    public void execute(Tuple tuple) {
        // "keyPBRB", "valuePBRB"
        String key = tuple.getStringByField("key");
        String value = tuple.getStringByField("value");

        try {
            if (StringUtils.isNotBlank(value) && value.length() > 4) {
                String[] lines = value.split(",", 2);
                // String id = tuple.getStringByField("id");
                if (lrange.contains(lines[0])) {
                    if (StringUtils.isNotBlank(pac) && !pac.equals(jsonPAC.get(lines[0]).toString()))
                        this.collector.emit(new Values(pac + key, "over"));
                    pac = jsonPAC.get(lines[0]).toString();
                    this.collector.emit(new Values(pac + key, value));
                }
            } else if (value.equals("over")) {
                this.collector.emit(new Values(pac + key, "over"));
            } else if (value.equals("jies")) {
                this.collector.emit(new Values(pac + key, "jies"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            this.collector.ack(tuple);
        }
    }


    @Override
    public void declareOutputFields(OutputFieldsDeclarer declarer) {
        declarer.declare(new Fields("key", "value"));
    }
}